from rest_framework import viewsets
from rest_framework.decorators import api_view, permission_classes
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView

from .serializers import UserSerializers, GroupSerializers, UserListSerializers, UserCreateSerializers, \
    UserRetrieveSerializers, UserUpdatePasswordSerializers
from django.contrib.auth.models import User, Group
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins

from .permissions import IsSuperUser
from rest_framework import permissions


class UserViewSets(viewsets.ModelViewSet):
    """
    模型视图集合
    queryset:    指明序列化目标
    serializer_class: 指明使用哪个类来进行序列化
    """
    queryset = User.objects.all()
    serializer_class = UserSerializers


class GroupViewSets(viewsets.ModelViewSet):
    """
    模型视图集合
    queryset:    指明序列化目标
    serializer_class: 指明使用哪个类来进行序列化
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializers


class UserListView(APIView):
    def get(self, req):
        users = User.objects.all()
        seria = UserSerializers(instance=users, many=True, context={"request": req})
        return Response(data={
            "code": 0,
            "msg": "获取用户列表",
            "data": seria.data
        }, status=status.HTTP_200_OK)

    def post(self, req):
        try:
            data = req.data
            seria = UserSerializers(data=data, context={"request": req})
            seria.is_valid(raise_exception=True)
            seria.save()
            return Response(data={
                "code": 0,
                "msg": "创建用户",
                "data": seria.data
            }, status=status.HTTP_201_CREATED)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)


class UserDetailView(APIView):
    def get(self, req, pk):
        try:
            user = User.objects.get(pk=pk)
            seria = UserSerializers(instance=user, context={"request": req})
            return Response(data={
                "code": 0,
                "msg": "获取用户信息",
                "data": seria.data
            }, status=status.HTTP_200_OK)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)

    def put(self, req, pk):
        try:
            user = User.objects.get(pk=pk)
            data = req.data
            seria = UserSerializers(instance=user, data=data, context={"request": req})
            seria.is_valid(raise_exception=True)
            seria.save()
            return Response(data={
                "code": 0,
                "msg": "修改用户信息",
                "data": seria.data
            }, status=status.HTTP_200_OK)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)

    def delete(self, req, pk):
        try:
            user = User.objects.get(pk=pk)
            user.delete()
            return Response(data={
                "code": 0,
                "msg": "删除用户",
            }, status=status.HTTP_204_NO_CONTENT)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)


class GroupListView(APIView):
    def get(self, req):
        groups = Group.objects.all()
        seria = GroupSerializers(instance=groups, many=True, context={"request": req})
        return Response(data={
            "code": 0,
            "msg": "获取用户组列表",
            "data": seria.data
        }, status=status.HTTP_200_OK)

    def post(self, req):
        try:
            data = req.data
            seria = GroupSerializers(data=data, context={"request": req})
            seria.is_valid(raise_exception=True)
            seria.save()
            return Response(data={
                "code": 0,
                "msg": "创建用户组",
                "data": seria.data
            }, status=status.HTTP_201_CREATED)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)


class GroupDetailView(APIView):
    def get(self, req, pk):
        try:
            group = Group.objects.get(pk=pk)
            seria = GroupSerializers(instance=group, context={"request": req})
            return Response(data={
                "code": 0,
                "msg": "获取用户组详情",
                "data": seria.data
            }, status=status.HTTP_200_OK)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)

    def put(self, req, pk):
        try:
            group = Group.objects.get(pk=pk)
            data = req.data
            seria = GroupSerializers(instance=group, data=data, context={"request": req})
            seria.is_valid(raise_exception=True)
            seria.save()
            return Response(data={
                "code": 0,
                "msg": "修改用户组信息",
                "data": seria.data
            }, status=status.HTTP_200_OK)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)

    def delete(self, req, pk):
        try:
            group = Group.objects.get(pk=pk)
            group.delete()
            return Response(data={
                "code": 0,
                "msg": "删除用户组",
            }, status=status.HTTP_204_NO_CONTENT)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)


class UserListCreateGenericView(ListCreateAPIView):

    def get_queryset(self):
        return User.objects.all()

    def get_serializer_class(self):
        return UserSerializers


class UserDetailRetrieveUpdateDestroyGenericView(RetrieveUpdateDestroyAPIView):
    lookup_field = "pk"

    def get_queryset(self):
        return User.objects.all()

    def get_serializer_class(self):
        return UserSerializers


class GroupListCreateGenericView(ListCreateAPIView):

    def get_queryset(self):
        return Group.objects.all()

    def get_serializer_class(self):
        return GroupSerializers


class GroupDetailRetrieveUpdateDestroyGenericView(RetrieveUpdateDestroyAPIView):
    lookup_field = "pk"

    def get_queryset(self):
        return Group.objects.all()

    def get_serializer_class(self):
        return GroupSerializers


class UserGenericViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, GenericViewSet):
    """
    用户视图集
    """

    def get_permissions(self):
        if self.action == "list":
            return [IsSuperUser()]
        elif self.action == "create":
            return [permissions.AllowAny()]

    def get_queryset(self):
        return User.objects.all()

    def get_serializer_class(self):
        if self.action == "list":
            return UserListSerializers
        elif self.action == "create":
            return UserCreateSerializers


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def update_password(req):
    data = req.data
    seria = UserUpdatePasswordSerializers(instance=req.user, data=data)
    seria.is_valid(raise_exception=True)
    seria.save()
    return Response(data=seria.data, status=status.HTTP_200_OK)


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def get_user_info(req):
    seria = UserRetrieveSerializers(instance=req.user, context={'request', req})
    return Response(data=seria.data, status=status.HTTP_200_OK)


class GroupGenericViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin,
                          mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericViewSet):
    """
    用户组视图集
    """
    lookup_field = "pk"

    def get_queryset(self):
        return Group.objects.all()

    def get_serializer_class(self):
        return GroupSerializers
